package com.sunstar.liveplugin.util

import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.util.Log
import android.widget.Toast
import com.faceunity.wrapper.faceunity
import com.netease.LSMediaCapture.lsLogUtil
import com.netease.LSMediaCapture.lsMediaCapture
import com.netease.LSMediaCapture.lsMessageHandler
import com.netease.vcloud.video.effect.VideoEffect
import com.netease.vcloud.video.render.NeteaseView
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.core.Observable
import io.reactivex.rxjava3.schedulers.Schedulers
import java.util.*
import java.util.concurrent.TimeUnit

class LiveInstance private constructor() {
    private var lsMediaCapturePara: lsMediaCapture.LsMediaCapturePara? = null
    private var mediaCapture: lsMediaCapture? = null
    private var mLiveStreamingPara: lsMediaCapture.LiveStreamingPara? = null
    private var waterMarkerBitmap: Bitmap? = null

    companion object {
        val Instance: LiveInstance by lazy {
            LiveInstance()
        }
    }

    init {
        lsMediaCapturePara = lsMediaCapture.LsMediaCapturePara()
    }

    ///初始化参数配置
    fun initLiveConfig(ctx: Context, handle: lsMessageHandler) {
        lsMediaCapturePara?.run {
            setContext(ctx)
            setMessageHandler(handle)
            setLogLevel(lsLogUtil.LogLevel.INFO)
            setUploadLog(false)
            mediaCapture = lsMediaCapture(this)
//            mediaCapture?.setSourceType(lsMediaCapture.SourceType.CustomAudio)
        }

        mLiveStreamingPara = lsMediaCapture.LiveStreamingPara()
    }

    ///设置直播参数
    fun initVideoStreamingPara(streamType: lsMediaCapture.StreamType): LiveInstance {
        mLiveStreamingPara?.run {
            setStreamType(streamType)
            setFormatType(lsMediaCapture.FormatType.RTMP_AND_MP4)
            isQosOn = true
            setQosEncodeMode(2)
        }
        return this
    }

    ///修改方向
    fun changeOrigation() {
        mediaCapture?.onConfigurationChanged()
    }

    ///视频预览
    fun videoPreview(view: NeteaseView, isFaceU: Boolean): LiveInstance {
        mediaCapture?.startVideoPreview(view, true, !isFaceU, lsMediaCapture.VideoQuality.HD1080P, true)
        FaceUUtil.instance.rebuildFrame().rebuildBeauty()
        Observable.timer(200, TimeUnit.MILLISECONDS).observeOn(AndroidSchedulers.mainThread()).subscribe {
            mediaCapture?.onConfigurationChanged()
        }
//        mediaCapture?.setCaptureRawDataCB { bytes, id, w, h, orientation ->
//            if (faceunity.fuIsLibraryInit() == 1) {
//                val mInputTextureType = 1; //输入的图像texture类型，Camera提供的默认为EXTERNAL OES
//                val mInputImageFormat = 0;
//                val flags = mInputTextureType or mInputImageFormat
//                faceunity.fuDualInputToTexture(bytes, id, flags, w, h, FaceUUtil.instance.frameId++, FaceUUtil.instance.beautyArray)
//            } else
//                0
//        }
        return this
    }

    fun initWhite(whiteColorPercent: Double, redColorPercent: Double, blurPercent: Double, filterName: String, filterPercent: Double) {
        FaceUUtil.instance.initWhite(whiteColorPercent, redColorPercent, blurPercent, filterName, filterPercent)
    }

    ///结束销毁
    fun onDestroy() {
        mediaCapture?.run {
            stopLiveStreaming()
            stopVideoPreview()
            destroyVideoPreview()
            releaseMessageHandler()
            uninitLsMediaCapture(false)
        }
        FaceUUtil.instance.destory()
        waterMarkerBitmap?.recycle()
        System.gc()
        waterMarkerBitmap = null
        mediaCapture = null
    }


    ///设置滤镜
    fun changeFilter(type: VideoEffect.FilterType) {

        mediaCapture?.setFilterType(type)
    }

    ///切换摄像头
    fun switchCamera() {
        mediaCapture?.switchCamera()
    }

    ///设置滤镜等级
    fun changeFilterLevel(value: Double) {
        mediaCapture?.setFilterStrength(value.toFloat())
    }

    ///修改美颜级别
    fun changeBeautyLevel(argument: Double) {
        mediaCapture?.setBeautyLevel(argument.toInt())
    }

    ///添加水印
    fun addWorkMarker(ctx: Context, x: Int, y: Int) {
        Observable.just(1).map {
            var input = ctx.assets.open("logo.png")
            waterMarkerBitmap = BitmapFactory.decodeStream(input)
            waterMarkerBitmap
        }.subscribeOn(Schedulers.newThread()).observeOn(AndroidSchedulers.mainThread()).subscribe {
            waterMarkerBitmap.run {
                mediaCapture?.setWaterMarkPara(this, VideoEffect.Rect.rightTop, x, y)
                mediaCapture?.setWaterPreview(true)
            }

        }

    }

    ///开始半音
    fun startPlayMusic(urlPath: String, isLoop: Boolean) {
        mediaCapture?.startPlayMusic(urlPath, isLoop)
    }

    ///视频方向尺寸计算
    fun changeScreenConfig() {
        mediaCapture?.onConfigurationChanged()
    }

    ///开始推流
    fun startPush(context: Context, pushPath: String) {
        mediaCapture?.run {
            initLiveStream(mLiveStreamingPara, pushPath)
            Observable.just(pushPath).map {
                startLiveStreaming()
            }.subscribeOn(Schedulers.newThread()).observeOn(AndroidSchedulers.mainThread()).subscribe {
                Toast.makeText(context, "推流成功，开始直播啦~", Toast.LENGTH_SHORT).show()
            }

        }
    }

    ///美颜功能初始化
    fun initFaceUnity(context: Context, array: ByteArray) {
        var v3 = context.assets.open("v3.bundle")
        Observable.just(v3).map {
            val v3Data = ByteArray(v3.available())
            v3.read(v3Data)
            v3.close()
            faceunity.fuSetup(v3Data, array)
        }.map {
            var beautyData: ByteArray? = ByteArray(0)
            if (it != 0) {
                var beauty = context.assets.open("face_beautification.bundle")
                beautyData = ByteArray(beauty.available())
                beauty.read(beautyData)
                beauty.close()
            }
            beautyData
        }.subscribeOn(Schedulers.newThread()).observeOn(AndroidSchedulers.mainThread()).subscribe {
            if (it != null) {
                FaceUUtil.instance.initBeautyData(it)
            }
        }
    }


    ///停止推流，暂时不用
    fun stopLiveStreaming() {
        mediaCapture?.stopLiveStreaming()
    }

    ///停止推送视频，暂时不用
    fun pauseVideoLiveStream() {
        mediaCapture?.pauseVideoLiveStream()
    }

    ///恢复推送视频，暂时不用
    fun resumeVideoLiveStream() {
        mediaCapture?.resumeVideoEncode()
    }

    ///添加监听回调
    fun addListener(handle: lsMessageHandler) {
        lsMediaCapturePara?.setMessageHandler(handle)
    }

    fun pausePush(){
        mediaCapture?.backgroundAudioEncode()
        mediaCapture?.backgroundVideoEncode()
    }

    fun repush(){
        mediaCapture?.resumeAudioEncode()
        mediaCapture?.resumeVideoEncode()
    }

}